package com.sunfeng.jksj.p25;

import com.sunfeng.TimeUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @Author : 孙峰
 * @Description: 对上面的 最优价格程序进一步优化
 * @Date : 2022/3/3  9:13
 */
@Slf4j(topic = "c.Demo03")
public class Demo03 {
    public static void main(String[] args) {

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //  创建completionService
        ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);
        // 创建 用于保存Future 的对象

        ArrayList<Future> futures = new ArrayList<>(3);

        futures.add(completionService.submit(() -> {
            TimeUtils.sleep(4);
            return 100;
        }));
        futures.add(completionService.submit(() -> {
            TimeUtils.sleep(3);
            return 30;
        }));
        futures.add(completionService.submit(() -> {
            TimeUtils.sleep(2);
            return 20;
        }));
        // 获取最快返回的结果
        Integer r = null;
        try {
            for (int i = 0; i < 3; i++) {
                r = completionService.take().get();
                if (r != null) {
                    break;
                }
            }
        } catch (Exception e) {

        } finally {
            for (Future future : futures) {
                future.cancel(true);
            }
        }
        log.info("返回结果为：" + r);
    }
}
